//
//  JXRandomNumbers.m
//  Open Lottery
//
//  Created by Shon on 8/10/09.
//  Copyright 2009 Praxxium Systems, LLC. All rights reserved.
//

#import "JXRandomNumbers.h"


@implementation JXRandomNumbers

-(id) initWithSeed:(NSData *)data {
    self = [super init];
    
    for(i=0; i<256; i++) S[i] = i;
    for(i=j=0; i<256; i++) {
        uint8 t;
        j = (j + [data bytes][i % [data length]] + S[i]) & 255;
        t = S[i];
        S[i] = S[j];
        S[j] = t;
    }
    
    i=j=0;
    
    return self;
}

- (void) skipBytes:(uint32)count { uint32 k; for(k=0;k<count;k++) [self nextByte]; }

- (uint8) nextByte {
    uint8 t;
    
    i = (i + 1) & 255;
    j = (j + S[i]) & 255;
    
    t = S[j];
    S[j] = S[i];
    S[i] = t;
    
    return S[(t + S[j]) & 255];
}

- (NSData *) nextBytes:(uint32)count {
    NSMutableData *md = [NSMutableData dataWithLength:count];
    uint8 *bytes = [md mutableBytes];
    uint32 k;
    for(k=0; k<count; k++) {
        bytes[k] = [self nextByte];
    }
    
    return [NSData dataWithData:md];
}

- (double) nextNormalized {
    double n = (double)[self nextByte];
    return n / 255.0;
}

@end
